package 容器;

import thread.MyConsumer;

import java.util.Arrays;
import java.util.Objects;

public class MyArrayList<E> {
    private Object[] elementData;
    private int size;//记录元素个数
    private int DEFAULT_CAPACITY = 10;

    @Override
    public String toString() {
        if (size == 0){
            return "[]";
        }
        StringBuffer str = new StringBuffer();
        str.append('[');
        for (int i = 0; i < size-1; i++) {
            str.append(elementData[i] + ", ");
        }
        str.append(elementData[size-1]+"]");
        return str.toString();
    }

    public boolean add(E e){
        if (elementData == null){
            elementData = new Object[]{};
        }
        if (elementData.length == size){
            grow();
        }
        elementData[size++] = e;
        return true;
    }

    //扩容算法
    private void grow() {
        if (size == 0){
            elementData = new Object[DEFAULT_CAPACITY];
        }else {
            elementData = Arrays.copyOf(elementData,elementData.length + (elementData.length >> 1));
        }
        
    }

    public E get(int index){
        checkIndex(index);
        return (E) elementData[index];
    }
    
    public void checkIndex(int index){
        if (index < 0 || index >= size){
            throw new IndexOutOfBoundsException(index + "out if max length " + size);
        }
        
    }


    public E remove(int index){
        checkIndex(index);
        E e = (E) elementData[index];
        int moveFlag = size - index - 1;
        if (moveFlag != 0){
            System.arraycopy(elementData,index + 1,
                    elementData, index, moveFlag);
        }
        elementData[--size] = null;
        return e;
    }
    
    public int size(){
        return size;
    }
    
    public void forEach(MyConsumer<E> action){
        Objects.requireNonNull(elementData);
        for (int i = 0; i < size; i++) {
            action.accept((E) elementData[i]);
        }
    }
}
